package com.pdg.dungeondelver.configuration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;
import org.newdawn.slick.util.xml.XMLElement;
import org.newdawn.slick.util.xml.XMLElementList;
import org.newdawn.slick.util.xml.XMLParser;

public class MapManager {
	
	private Map<String,CQMFile> maps = new HashMap<String,CQMFile>();

	public CQMFile get(String theMap){
		return maps.get(theMap);
	}
	
	private Theme theme;
	
	public Theme getTheme(){
		return theme;
	}

	public MapManager(Theme theTheme, String mapsConfiguration) throws MapManagerLoadException {
		setTheme(theTheme);
		if(!loadFromXml(mapsConfiguration)){
			throw new MapManagerLoadException();
		}
	}

	private boolean loadFromXml(String mapsConfiguration) {
		XMLParser parser = new XMLParser();
		XMLElement root;
		try {
			InputStream stream = ResourceLoader.getResourceAsStream(mapsConfiguration);
			root = parser.parse(mapsConfiguration,stream);
			XMLElementList children = root.getChildren();
			for(Integer index=0;index<children.size();++index){
				XMLElement child = children.get(index);
				maps.put(child.getName(),new CQMFile(child.getContent()));
			}
			return true;
		} catch (SlickException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (CQMFileLoadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	private void setTheme(Theme theTheme) {
		theme = theTheme;
	}

}
